/**
 * 接种点管理员主页JavaScript逻辑
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.SITE_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

function normalizeAppointmentPage(data) {
    if (!data) {
        return [];
    }
    if (Array.isArray(data)) {
        return data;
    }
    if (Array.isArray(data.records)) {
        return data.records;
    }
    return [];
}

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 显示当前日期
    displayCurrentDate();
    
    // 检查并显示低库存预警
    await checkAndShowLowStockAlert();
    
    // 加载今日预约
    await loadTodayAppointments();
    
    // 加载低库存预警
    await loadLowStockAlerts();
    
    // 加载库存统计
    await loadInventoryStats();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '管理员';
        document.getElementById('userName').textContent = userName;
        document.getElementById('welcomeName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 显示当前日期
 */
function displayCurrentDate() {
    const now = new Date();
    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    const dateStr = now.toLocaleDateString('zh-CN', options);
    document.getElementById('currentDate').textContent = dateStr;
}

/**
 * 加载今日预约
 */
async function loadTodayAppointments() {
    try {
        const pageData = await HttpClient.get('/admin/appointment/today');
        const appointments = normalizeAppointmentPage(pageData);
        
        // 更新统计数字
        document.getElementById('todayAppointments').textContent = appointments.length;
        
        // 统计已完成数量
        const completed = appointments.filter(a => a.appointmentStatus === 1).length;
        document.getElementById('completedToday').textContent = completed;
        
        // 显示预约列表（只显示前5条）
        displayTodayAppointments(appointments.slice(0, 5));
    } catch (error) {
        console.error('加载今日预约失败:', error);
        UI.showMessage('加载今日预约失败', 'danger');
    }
}

/**
 * 显示今日预约列表
 */
function displayTodayAppointments(data) {
    const appointments = normalizeAppointmentPage(data);
    const tbody = document.getElementById('todayAppointmentsBody');
    tbody.innerHTML = '';
    
    if (!appointments || appointments.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="5" style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                    今日暂无预约
                </td>
            </tr>
        `;
        return;
    }
    
    appointments.forEach(appointment => {
        const row = document.createElement('tr');
        
        // 判断是否可以更新状态（只有待接种状态才能更新）
        const canUpdate = appointment.appointmentStatus === 0;
        const updateButton = canUpdate ? 
            `<button class="btn btn-success btn-sm" onclick="updateAppointmentStatus(${appointment.id})">
                <i class="fas fa-check"></i> 完成接种
            </button>` : 
            `<span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                ${Format.appointmentStatus(appointment.appointmentStatus)}
            </span>`;
        
        row.innerHTML = `
            <td>${appointment.personName || '-'}</td>
            <td>${appointment.vaccineName || '-'}</td>
            <td>${Format.datetime(appointment.appointmentTime)}</td>
            <td>
                <span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                    ${Format.appointmentStatus(appointment.appointmentStatus)}
                </span>
            </td>
            <td>${updateButton}</td>
        `;
        tbody.appendChild(row);
    });
}

/**
 * 加载低库存预警
 */
async function loadLowStockAlerts() {
    try {
        const alerts = await HttpClient.get('/admin/inventory/low-stock-alert');
        
        // 更新统计数字
        document.getElementById('lowStockCount').textContent = alerts.length;
        
        // 显示预警列表
        displayLowStockAlerts(alerts);
    } catch (error) {
        console.error('加载低库存预警失败:', error);
    }
}

/**
 * 显示低库存预警列表
 */
function displayLowStockAlerts(alerts) {
    const tbody = document.getElementById('lowStockBody');
    tbody.innerHTML = '';
    
    if (!alerts || alerts.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="5" style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-check-circle" style="font-size: 48px; margin-bottom: 10px; display: block; color: #4caf50;"></i>
                    库存充足，暂无预警
                </td>
            </tr>
        `;
        return;
    }
    
    alerts.forEach(alert => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${alert.vaccineName || '-'}</td>
            <td><span style="color: #f5222d; font-weight: bold;">${alert.quantity || 0}</span></td>
            <td>${alert.lowStockThreshold || 100}</td>
            <td>${Format.date(alert.productionDate)}</td>
            <td>${Format.date(alert.expirationDate)}</td>
        `;
        tbody.appendChild(row);
    });
}

/**
 * 加载库存统计
 */
async function loadInventoryStats() {
    try {
        const inventories = await HttpClient.get('/admin/inventory/list');
        
        // 更新库存种类数量
        document.getElementById('totalInventory').textContent = inventories.length;
    } catch (error) {
        console.error('加载库存统计失败:', error);
    }
}

/**
 * 更新预约状态
 */
async function updateAppointmentStatus(appointmentId) {
    UI.confirm('确定要将此预约标记为已完成吗？', async () => {
        try {
            await HttpClient.put(`/admin/appointment/${appointmentId}/status`, { status: 1 });
            
            UI.showMessage('更新状态成功', 'success');
            
            // 重新加载今日预约
            await loadTodayAppointments();
        } catch (error) {
            console.error('更新状态失败:', error);
            UI.showMessage(error.message || '更新状态失败', 'danger');
        }
    });
}

/**
 * 检查并显示低库存预警
 */
async function checkAndShowLowStockAlert() {
    try {
        // 检查sessionStorage中是否已关闭预警（本次会话）
        const alertClosed = sessionStorage.getItem('lowStockAlertClosed');
        if (alertClosed === 'true') {
            return; // 用户已关闭预警，本次会话不再显示
        }
        
        // 获取低库存预警列表（阈值10）
        const alerts = await HttpClient.get('/admin/inventory/low-stock-alert?threshold=10');
        
        if (alerts && Array.isArray(alerts) && alerts.length > 0) {
            // 有低库存预警，显示提示条
            const alertBar = document.getElementById('lowStockAlertBar');
            const alertText = document.getElementById('lowStockAlertText');
            const mainContent = document.getElementById('mainContent');
            
            if (alertBar && alertText && mainContent) {
                // 统计低库存疫苗数量
                const vaccineCount = new Set(alerts.map(a => a.vaccineId).filter(id => id != null)).size;
                alertText.textContent = `检测到 ${alerts.length} 个低库存预警（涉及 ${vaccineCount} 种疫苗），请及时补充库存`;
                
                alertBar.classList.add('show');
                mainContent.classList.add('has-alert');
            }
        }
    } catch (error) {
        console.error('检查低库存预警失败:', error);
    }
}

/**
 * 关闭低库存预警提示
 */
function closeLowStockAlert() {
    const alertBar = document.getElementById('lowStockAlertBar');
    const mainContent = document.getElementById('mainContent');
    
    if (alertBar) {
        alertBar.classList.remove('show');
    }
    if (mainContent) {
        mainContent.classList.remove('has-alert');
    }
    
    // 记录用户关闭了预警（本次会话有效）
    sessionStorage.setItem('lowStockAlertClosed', 'true');
}

/**
 * 退出登录
 */
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        Auth.logout();
    }
}

